from typing import final

from server.apps.blog.infrastructure.forms import SimpleScoreForm
from server.apps.blog.logic.posts import commands
from server.apps.blog.models import Post


@final
class Failed(Exception):
    """
    This is a domain error.

    It means, that we are not able to rate this post.
    Details are stored in the ``.context`` property.
    """

    def __init__(self, instance: Post, form: SimpleScoreForm) -> None:
        super().__init__()
        self.context = {'form': form, 'instance': instance}


def run(
    instance: Post,
    form: SimpleScoreForm,
) -> None:
    """Updates score of an existing post."""
    score = form.get_valid_score()
    if score is None:
        raise Failed(instance, form)
    commands.update_score(instance.id, score)
